import sys
import codecs
import re
import subprocess
import os
import string

from config import Config

def ShaggerVersion():
    return 1.3

def nicecommand():
    if Config['niceness'] == 0:
        return []
    return ["nice", "-n", "%d" % Config['niceness'] ]

def mypopen(array, stdout = 0, stdin = 0):
    return subprocess.Popen( nicecommand() + array, stdout = stdout, stdin = stdin)

#Shamelessly stolen from 
#http://www.megasolutions.net/python/Issue-of-redirecting-the-stdout-to-both-file-and-screen-78646.aspx
class TeeNoFile(object):
    def __init__(self, name, pipe = "out", mode = 'w'):
        self.file = codecs.open(name, mode = mode, encoding='utf-8')
        self.pipe = pipe #can you pass by reference somehow?
         
        if pipe == "out":                  
            self.stdout = sys.stdout             
            sys.stdout = self
        else:
            if pipe == "err":
                self.stdout = sys.stderr             
                sys.stderr = self
            else:
                #this is a problem
                raise(Exception)
            
    def close(self):
        if self.stdout is not None:
            if self.pipe == "out":
                sys.stdout = self.stdout
            else:
                sys.stderr = self.stdout
            self.stdout = None             
        if self.file is not None:
            self.file.close()
            self.file = None
    def write(self, data):
        try:
            data = unicode(data)
        except UnicodeDecodeError, err:
            #chances are it is already unicode, but whatever we're only logging right?
            data = unicode(data, 'utf-8', 'replace')
            
        self.file.write(data)
        try:
            self.stdout.write(data)
        except UnicodeEncodeError, err:
            self.stdout.write(data.encode("ascii", "replace"))
                  
    def flush(self):
        self.file.flush()
        self.stdout.flush()
    def __del__(self):
        self.close()

def trackstr(track):
    return "track%02d" % track

def parseTrackNum(filein):
    #TODO: Generalise?
    file = os.path.split(filein)[1]
    patterns = [
                "[Tt]rack(\d*)",
                "(\d*)[ -.,]",
                "split-[Tt]rack(\d*)"
                ]
    for pattern in patterns:
        #print("Parse track num: %s" % file)
        match = re.match(pattern, file)
        if match:
            intt = int(match.group(1))
            #print("hit %s" % intt)
            return intt #the number bit    
    
    return None

def parseTrackNumFromTag( tagin ):
    #some people insist on writing "1/10" when they mean 1 :(
    patterns = [
        "(\d*)"
        ];
    for pattern in patterns:
        #print("Parse track num: %s" % file)
        match = re.match(pattern, tagin)
        if match:
            intt = int(match.group(1))
            #print("hit %s" % intt)
            return intt #the number bit  
    return None

def GrokArtistFromPath(path):
    #self.shagger.log("Filename parsing isn't implemented yet, sorry")
    base, tail = os.path.split(os.path.abspath(path))
    match = re.match("(.*)-(.*)", tail)
    if match:
        return (match.group(1), match.group(2))
        
    match = re.match("(.*)_(.*)", tail)

    if match:
        return (match.group(1), match.group(2))
    
    return (None, None)
    #2nd is the directory name insightful?
        
    #3rd is the direcotry tree insightful?


def minimalistName(string):
    
    s = re.sub("[\[\{\(\<].*[\]\}\)\>]", "", string)
    s = s.strip()
    return(s)
    

def extractIdFromUrl(url):
    match = re.match("https?.*/.*\?.*id=([\w-]*)", url)
    if match:
        return match.group(1)
    match = re.match("https?.*/([\w-]*)(.html)?", url)
    if match:
        return match.group(1)
    
    match = re.match("([\w-]*)\s")
    if match:
        return match.group(1)
    
    return url

def sanitizeFileName(string):
    #Remove the things windows tends to choke on:
    #alternatively could remap them to whatever we like here
    str = unicode(string)
    map = {}
    map[ord(u':')] = None
    map[ord(u'*')] = None
    map[ord(u'\\')] = None
    map[ord(u'/')] = None
    map[ord(u'<')] = None
    map[ord(u'>')] = None
    map[ord(u'|')] = None
    map[ord(u'?')] = None
    str = str.translate(map)
    #print "Sanitised: %s" % filename
    return str

def makeSubmitHtml():
    dirs = os.listdir(Config['tempdir'])
    
    releases = allWorkingDiscs()
    urls = []
       
    for release in releases:
        submitfile = os.path.join(Config['tempdir'], release, Config['cdidfile'])
        cddbfile = os.path.join(Config['tempdir'], release, Config['cddbfile'])
        data = {}
        if(os.path.exists(submitfile)):
            f = open(submitfile, "r")
            data['url'] = string.rstrip(f.read())
            data['dir'] = release
            data['cddb'] = "???"
            f.close()
            
        if(os.path.exists(cddbfile)):
            f = open(cddbfile, "r")
            cddbdata = f.read()
            data['cddb'] = cddbdata.split("\n")[0]
            f.close()
        
        if( data.has_key("url")):
            urls = urls + [data]
            
    
    file = Config['submithtmlfile']
    f = open(file, "w")
    f.write("<html><head>Discs in progress</head>\n")
    f.write("<body>\n<h1>Discs in progress:</h1>\n")
    f.write("<ul>\n")
    for data in urls:
        f.write("<li><a href=\"%s\">%s: %s</a></li>\n" % (data['url'], data['dir'], data['cddb']))
    f.write("</ul>\n")
    f.write("</body></html>\n")
    f.close()
    
def allWorkingDiscs():
    dirs = os.listdir(Config['tempdir'])
    
    releases = []
    urls = []
    
    for dir in dirs:
        if len(dir) == 28:
            releases = releases + [dir]
    

    
    return releases    


 
